//
//  FindDealPasswordViewController.m
//  SSSMerchant
//
//  Created by Darker on 2017/4/8.
//  Copyright © 2017年 xnxin. All rights reserved.
//

#import "FindDealPasswordViewController.h"

@interface FindDealPasswordViewController ()<QMUITextFieldDelegate>
{
    
    UILabel *_phoneLabel;
    QMUITextField *_codeTextField;
    QMUITextField *_newPasWordTextField;
    QMUITextField *_surePasWordTextField;
    UIButton *_sureBtn;//确定按钮
}

/** 发送验证码按钮; */
@property (nonatomic, strong)UIButton *sendAuthCodeBtn;
/**
 *  装文本框的数组
 */
@property (nonatomic,strong)  NSMutableArray<QMUITextField *> *textFiledArray;

@end

@implementation FindDealPasswordViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.title = @"修改登录密码";
    //去掉透明后导航栏下边的黑边
    //    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    self.navigationController.navigationBar.hidden = NO;
    self.view.backgroundColor = [UIColor colorWithHex:@"F9F9FA"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setApperance];
    
}

- (void)setApperance{
    
    UIView *headerView = [[UIView alloc]init];
    [self.view addSubview:headerView];
    headerView.backgroundColor = [UIColor colorWithHex:@"FFFFFF"];
    headerView.layer.borderWidth = 0.5;
    headerView.layer.borderColor = [UIColor colorWithHex:@"E5E5E8"].CGColor;
    headerView.sd_layout
    .topSpaceToView(self.view,HeigthIos6CompeteWithCurrent(10) + 64)
    .leftEqualToView(self.view)
    .rightEqualToView(self.view)
    .heightIs(HeigthIos6CompeteWithCurrent(51));
    
    
    UILabel *phoneLabel = [[UILabel alloc]init];
    
    phoneLabel.text = [NSString stringWithFormat:@"手机号:%@", [SSSUserManager getUserModel].phone];
    phoneLabel.textColor = [UIColor colorWithHex:@"6D6D6D"];
    phoneLabel.textAlignment = NSTextAlignmentLeft;
    phoneLabel.font = [SSSFont systemFontOfSize:16];
    [headerView addSubview:phoneLabel];
    phoneLabel.sd_layout
    .centerYEqualToView(headerView)
    .leftSpaceToView(headerView,WidthIos6CompeteWithCurrent(25))
    .autoHeightRatio(0)
    .widthIs(WidthIos6CompeteWithCurrent(200));
    
    // 设置五个文本框
    // 占位文字的数组
    NSArray *placeHolders = @[@"请输入验证码",@"请输入新密码",@"请再次输入密码"];
    // 装图片名字的数组
    //NSArray *imageNamesArray = @[@"img_phone",@"icon_auth-code",@"img_password",@"img_password"];
    
    //发送验证码按钮
    _sendAuthCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_sendAuthCodeBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
    [_sendAuthCodeBtn setBackgroundColor:[UIColor colorWithHex:@"46B77D"]];
    [self.view addSubview:_sendAuthCodeBtn];
    _sendAuthCodeBtn.titleLabel.font = [SSSFont systemFontOfSize:14];
    //    _sendAuthCodeBtn.layer.borderColor = [[UIColor whiteColor] colorWithAlphaComponent:0.7].CGColor;
    //    _sendAuthCodeBtn.layer.borderWidth = 1;
    _sendAuthCodeBtn.layer.cornerRadius = HeigthIos6CompeteWithCurrent(10);
    _sendAuthCodeBtn.layer.masksToBounds = YES;
    [_sendAuthCodeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_sendAuthCodeBtn addTarget:self action:@selector(sendAuthCodeClick) forControlEvents:UIControlEventTouchDown];
    
    // 设置一个指针，指向文本框
    UITextField *currentFiled = nil;
    //添加文本框
    for (int index = 0; index < placeHolders.count; index++) {
        
        QMUITextField *textField = [[QMUITextField alloc]init];
        [self.textFiledArray addObject:textField];
        textField.returnKeyType = UIReturnKeyDone;
        textField.delegate = self;
        textField.tag = 300 +index;
        textField.font = [SSSFont systemFontOfSize:14];
        
        [self.view addSubview:textField];
        textField.placeholder = placeHolders[index];
        textField.textColor = [UIColor colorWithHex:@"000000"];
        [textField setValue:[UIColor colorWithHex:@"BBBBBB"] forKeyPath:@"_placeholderLabel.textColor"];
        textField.layer.borderWidth = 0.5;
        textField.layer.borderColor = [[UIColor grayColor] colorWithAlphaComponent:0.3].CGColor;
        textField.layer.cornerRadius = HeigthIos6CompeteWithCurrent(10);
        textField.layer.masksToBounds = YES;
        // 设置文本框的清楚按钮的模式
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        // 设置文本框的清楚按钮的模式
        textField.clearsOnBeginEditing = YES;
        // 设置文本框的光标颜色
        textField.tintColor = [UIColor colorWithHex:@"44b034"];
        // [self setLfetView:imageNamesArray[index] isLeft:YES textField:textField];
        //[self setLfetImageView:imageNamesArray[index] isLeft:YES textField:textField];
        
        //布局约束
        //ZD_WEAKSELF;
        [textField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view).offset(WidthIos6CompeteWithCurrent(43));
            
            if (textField.tag == 300) {
                make.right.equalTo(self.view).offset(WidthIos6CompeteWithCurrent(-163));
                
                //发送验证码按钮布局约束
                _sendAuthCodeBtn.sd_layout
                .topEqualToView(textField)
                .bottomEqualToView(textField)
                .rightSpaceToView(self.view,WidthIos6CompeteWithCurrent(43))
                .leftSpaceToView(textField,WidthIos6CompeteWithCurrent(15));
                
            }else{
                
                make.right.equalTo(self.view).offset(WidthIos6CompeteWithCurrent(-43));
            }
            make.height.equalTo(@(HeigthIos6CompeteWithCurrent(51)));
            if (currentFiled == nil) {
                make.top.equalTo(self.view).offset(HeigthIos6CompeteWithCurrent(25) + 64 + HeigthIos6CompeteWithCurrent(51) + HeigthIos6CompeteWithCurrent(10));
            }
            else {
                make.top.equalTo(currentFiled.mas_bottom).offset(HeigthIos6CompeteWithCurrent(15));
            }
        }];
        currentFiled = textField;
        if (index == 1) {
            textField.secureTextEntry = YES;
        }else if (index == 2){
            textField.secureTextEntry = YES;
        }
        
    }
    
    //确定按钮
    _sureBtn = [[UIButton alloc]init];
    [_sureBtn setTitle:@"确 定" forState:UIControlStateNormal];
    _sureBtn.titleLabel.font = [SSSFont systemFontOfSize:20];
    [_sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_sureBtn setBackgroundColor:[UIColor colorWithHex:@"40B87B"]];
    _sureBtn.layer.cornerRadius = HeigthIos6CompeteWithCurrent(10);
    _sureBtn.layer.masksToBounds = YES;
    [_sureBtn addTarget:self action:@selector(sureBtnClick) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:_sureBtn];
    
    //添加布局约束
    _sureBtn.sd_layout
    .topSpaceToView(currentFiled,HeigthIos6CompeteWithCurrent(30))
    .leftEqualToView(currentFiled)
    .rightEqualToView(currentFiled)
    .heightIs(HeigthIos6CompeteWithCurrent(51));
    
    //取消按钮
    
    UIButton *cancelBtn = [[UIButton alloc]init];
    [cancelBtn setTitle:@"取 消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor colorWithHex:@"46B77D"] forState:UIControlStateNormal];
    [cancelBtn setBackgroundColor:[UIColor clearColor]];
    cancelBtn.titleLabel.font = [SSSFont systemFontOfSize:20];
    [cancelBtn addTarget:self action:@selector(cancelBtnClick) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:cancelBtn];
    cancelBtn.sd_layout
    .topSpaceToView(_sureBtn,HeigthIos6CompeteWithCurrent(20))
    .leftEqualToView(_sureBtn)
    .rightEqualToView(_sureBtn)
    .heightIs(HeigthIos6CompeteWithCurrent(51));
    cancelBtn.layer.cornerRadius = HeigthIos6CompeteWithCurrent(10);
    cancelBtn.layer.masksToBounds = YES;
    cancelBtn.layer.borderColor = [UIColor colorWithHex:@"46B77D"].CGColor;
    cancelBtn.layer.borderWidth = 0.5;
    
    
}
#pragma mark - 发送验证码按钮
- (void)sendAuthCodeClick{
    
    // 让所有的文本框放弃第一响应者
    [self doResignFirstResponder];
    [self sendVerifyCodeWithSuccess:nil];
    
}
/**
 *  让所有的文本框放弃第一响应者的回调方法
 */
- (void)doResignFirstResponder {
    [self.textFiledArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj resignFirstResponder];
    }];
}
#pragma mark - 倒计时开始
- (void)verificationCodeOfTimer
{
    __block int timeout = 60.0; //倒计时时间
    ZD_WEAKSELF;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [weakSelf.sendAuthCodeBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
                weakSelf.sendAuthCodeBtn.userInteractionEnabled = YES;
                weakSelf.sendAuthCodeBtn.enabled = YES;
                [weakSelf.sendAuthCodeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                //                weakSelf.sendAuthCodeBtn.layer.borderColor = [[UIColor whiteColor] colorWithAlphaComponent:0.7].CGColor;
                [weakSelf.sendAuthCodeBtn setBackgroundColor:[UIColor colorWithHex:@"46B77D"]];
                //                weakSelf.sendAuthCodeBtn.layer.borderWidth = 1;
            });
            
        }else{
            int seconds = (timeout-1) % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                //NSLog(@"____%@",strTime);
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1];
                //                NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:str];
                //                //                [AttributedStr addAttribute:NSFontAttributeName
                //                //
                //                //                                      value:[UIFont systemFontOfSize:16.0]
                //                //
                //                //                                      range:NSMakeRange(0, 2)];
                //
                //                [AttributedStr addAttribute:NSForegroundColorAttributeName
                //
                //                                      value:[UIColor redColor]
                //
                //                                      range:NSMakeRange(0, 2)];
                //                //                [AttributedStr addAttribute:NSForegroundColorAttributeName
                //                //
                //                //                                      value:[UIColor grayColor]
                //                //
                //                //                                      range:NSMakeRange(2,6)];
                //
                
                [weakSelf.sendAuthCodeBtn setTitle:[NSString stringWithFormat:@"%@秒后重发",strTime] forState:UIControlStateNormal];
                [weakSelf.sendAuthCodeBtn setTitleColor:[UIColor colorWithHex:@"BBBBBB"]forState:UIControlStateNormal];
                weakSelf.sendAuthCodeBtn.layer.borderColor = [[UIColor grayColor] colorWithAlphaComponent:0.2].CGColor;
                weakSelf.sendAuthCodeBtn.layer.borderWidth = 0.5;                //                weakSelf.sendAuthCodeBtn.layer.borderColor = [[UIColor grayColor] colorWithAlphaComponent:0.7].CGColor;
                //                weakSelf.sendAuthCodeBtn.layer.borderWidth = 1;
                [UIView commitAnimations];
                weakSelf.sendAuthCodeBtn.userInteractionEnabled = NO;
                weakSelf.sendAuthCodeBtn.enabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}
#pragma mark - 确定按钮
- (void)sureBtnClick{
    if ([[self.textFiledArray[0] text] isEqualToString:@""]){
        showTipHudStr(@"请输入验证码");
        return;
    }
    
    if ([[self.textFiledArray[1] text] isEqualToString:@""]){
        showTipHudStr(@"请输入新密码");
        return;
    }
    
    if ([[self.textFiledArray[2] text] isEqualToString:@""]){
        showTipHudStr(@"请再次输入新密码");
        return;
    }
    
    if ([self.textFiledArray[1] text].length<6) {
        showTipHudStr(@"新密码不少于六位数");
        return;
        
    }
    if ([self.textFiledArray[1] text].length>20) {
        showTipHudStr(@"新密码不多于15位数");
        return;
    }
    
    if (![SSSRegularExpression checkPassword:[self.textFiledArray[1] text]]) {
        showTipHudStr(@"新密码只包含字母和数字");
        return;
        
    }
    if (![[self.textFiledArray[1] text] isEqualToString:[self.textFiledArray[2] text]]){
        showTipHudStr(@"两次输入密码不一致");
        return;
    }
    [self doResignFirstResponder];
    [self netForCodeWithSuccess:^(id responseObj){
        
        if (kResponseStatus == 0) {
            
            [QMUITips showSucceed:@"修改成功" inView:self.view hideAfterDelay:2];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
            
        }else{
            showTipHudStr(kResponseMessage);
        }
        
    }];
}
- (void)backSuperController{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}
#pragma mark - 取消按钮
- (void)cancelBtnClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}
/**
 *  点击空白处，让键盘消失
 *
 *  @param touches 手指触摸的地方
 *  @param event   手指触摸
 */
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 让所有的文本框放弃第一响应者
    [self doResignFirstResponder];
}

#pragma mark -  net
//发生送验证码
-(void)sendVerifyCodeWithSuccess:(void (^)())success{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"phone"] = [SSSUserManager getUserModel].phone;
    
    [ZDNetManager zd_requestWithType:ZDHttpRequestTypeGet UrlString:kConfigPath(kGetCode) Parameters:params SuccessBlock:^(id responseObj) {
        if (kResponseStatus == 0) {
            //倒计时
            [self verificationCodeOfTimer];
            
        }else{
            showTipHudStr(kResponseMessage);
        }
    } FailureBlock:^(NSError *error) {
        
        [QMUITips showError:error.localizedDescription inView:self.view hideAfterDelay:2];
        
    } progress:^(int64_t bytesProgress, int64_t totalBytesProgress) {
        
        
    }];
    
}
//提交
-(void)netForCodeWithSuccess:(void (^)(id response))success{
    NSMutableDictionary *parameter = [NSMutableDictionary dictionary];
    parameter[@"transactionPwd"] = _textFiledArray[2].text;
    parameter[@"phone"] = [SSSUserManager getUserModel].phone;
    parameter[@"code"] = _textFiledArray[0].text;
    
    [[XHRequestManager manager] postRequest:kConfigPath(kFindTradeCode) params:parameter success:^(id  _Nonnull responseObj) {
        
        if (kResponseStatus==0) {
            [QMUITips showSucceed:@"设置交易密码成功" inView:kKeyWindow hideAfterDelay:1];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
            
        }
        else showTipHudStr(kResponseMessage);
        
    } failure:^(NSError * _Nonnull error) {
        
        [QMUITips showError:error.localizedDescription inView:self.view hideAfterDelay:2];
    }];
//    
//    [ZDNetManager zd_requestWithType:ZDHttpRequestTypePost UrlString:kConfigPath(kFindTradeCode) Parameters:parameter SuccessBlock:^(id response) {
//        
//        if (kResponseStatus==0) {
//            [QMUITips showSucceed:@"设置交易密码成功" inView:kKeyWindow hideAfterDelay:1];
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [self.navigationController popViewControllerAnimated:YES];
//            });
//            
//        }
//        else showTipHudStr(kResponseMessage);
//        
//    } FailureBlock:^(NSError *error) {
//        
//        [QMUITips showError:error.localizedDescription inView:self.view hideAfterDelay:2];
//    } progress:^(int64_t bytesProgress, int64_t totalBytesProgress) {
//        
//        
//    }];
    
}

/**
 *  懒加载，初始化数组
 *
 *  @return 返回一个初始化好的数组
 */
- (NSMutableArray *)textFiledArray {
    if (!_textFiledArray) {
        _textFiledArray = [NSMutableArray array];
    }
    return _textFiledArray;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
